/*
 * @Author: CodeHare
 * @Date: 2023-10-16 19:16:04
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-10 15:06:58
 * @Description: 空调参数设置
 */

import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_obj/data_type_model.dart';
import 'package:yt_devops/model/device_obj/output_data_model.dart';
import 'package:yt_devops/model/device_obj/services_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/air_condition_setting/air_condition_setting_model.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class AirConditionSettingController extends GetxController {
  DeviceServices deviceServices = DeviceServices();

  AirConditionSettingModel model = AirConditionSettingModel();

  /// 设备 id
  var deviceId;

  ///
  int? productId;

  /// 是否自研风冷
  bool isSelfDevice = false;

  /// 订阅 websocket-网络状态
  ConnectStatusType? connectStatus = ConnectStatusType.off;
  UseSubsribe onlineStatusSubsribe = UseSubsribe();
  late Stream<Map<String, dynamic>> onlineStatusBroadcastStream;
  StreamSubscription<Map<String, dynamic>>? onlineStatusSubscription;

  /// 订阅 websocket-设置值
  UseSubsribe subsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? subscription;
  late Stream<Map<String, dynamic>> broadcastStream;

  Map<String, dynamic>? dataSource = {};
  late int currentRole;

  /// 物模型指令集合
  List<OutputDataModel> outputList = [];
  bool isHidden = false;
  bool success = false;
  int editType = -1;

  bool get bwtAirSetting => productId == ProductIDType.bWattAir.value;

  @override
  void onInit() {
    deviceId = Get.arguments['deviceId'];
    productId = Get.arguments['productId'];
    currentRole = UserEntityManager().userModel.roles![0].roleId!;
    isSelfDevice = productId == ProductIDType.yTEnergyAir.value ? true : false;
    initPage();

    super.onInit();
  }

  /// @description: 初始化页面
  /// @return {*}
  void initPage() async {
    showLoading(toast: ResKey.loading.tr);
    // readPhysicalModel();
    await getPhysicalModel();
    listenOnlineStatus();
    initDefaultData();
  }

  /// @description: 读取物模型
  /// @return {*}
  // void readPhysicalModel() {
  //   var services = deviceTabController.services;
  //   initRunningParamsModel(services);
  //   initFixedValueParamsModel(services);
  //   recurOutputKeys();
  //   update();
  // }

  /// @description: 获取物模型
  /// @return {*}
  Future getPhysicalModel() => Configs.httpClient.requestWithLoading(() async {
        try {
          var data =
              await deviceServices.getDeviceProperty({'productId': productId});

          /// 自研设备（风冷、液冷）
          if (data['services'] != null) {
            var services = data['services'];

            if (productId == ProductIDType.bWattAir.value) {
              initRunningParamsModel(services[0]);
              model.fixedParameterModel =
                  model.getBwtFixedParameterModel(data['properties']);
            } else if (productId == ProductIDType.yTEnergyAir.value) {
              initFixedValueParamsModel(services[1]);
              initRunningParamsModel(services[0]);
            }
          } else {
            /// 比瓦特、矩形（后续补充，其物模型无 services 字段）
          }

          recurOutputKeys();
          update();
        } catch (e) {
          print(e);
        }
      }, showLoading: false);

  /// @description: 初始化定值参数设置
  /// @return {*}
  void initFixedValueParamsModel(services) {
    model.fixedParameterModel = ServicesModel.fromJson(services);
  }

  /// @description: 初始化运行参数设置
  /// @return {*}
  void initRunningParamsModel(services) {
    model.runParameterModel = ServicesModel.fromJson(services);
  }

  /// @description:  递归获取物模型下每个指令集合
  /// @return {*}
  void recurOutputKeys() {
    var settings = [
      model.runParameterModel,
      model.fixedParameterModel,
    ];

    outputList.clear();

    for (var element in settings) {
      List<OutputDataModel> outs = element?.outputData ?? [];
      for (var o in outs) {
        outputList.add(o);
      }
    }
  }

  /// @description: 初始化设置默认值
  /// @return {*}
  void initDefaultData() {
    broadcastStream =
        subsribe.start([deviceId!], true).stream.asBroadcastStream();

    subscription = broadcastStream.listen((data) {
      assignSocket(data);
    });
    dismissLoading();
  }

  /// 初始化数据
  void assignSocket(Map<String, dynamic>? dataSource) {
    dataSource?.forEach((key, value) {
      var idx = outputList.indexWhere((element) => element.id == key);
      if (idx > -1) {
        var data = value;
        if (outputList[idx].dataType.type == DataTypeEnum.array) {
          data = jsonDecode(value);
        }
        model.deviceData.addAll({key: data});
      }

      update();
    });
  }

  /// 监听设备在线状态
  void listenOnlineStatus() {
    onlineStatusBroadcastStream = onlineStatusSubsribe
        .start([deviceId], true, type: MessageEventType.networkStatus)
        .stream
        .asBroadcastStream();

    onlineStatusSubscription = onlineStatusBroadcastStream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
          $ConnectStatusTypeEnumMap,
          data['networkStatus'],
        );
      }
    });
  }

  /// @description: 点击下发参数
  /// @return {*}
  void onClick(int type) {
    if (connectStatus == ConnectStatusType.off) return;
    editType = type;
    update();
  }

  /// @description: 下发指令接口
  /// @return {*}
  Future sendCommand(context, params) => Configs.httpClient.requestWithLoading(
        () async {
          await deviceServices.deviceRemoteSetting(jsonDecode(params));
          success = true;
          FuncUtils.requestTipsDislog(context, ResKey.executeSuccess.tr, true);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          update();
        },
        onError: (err) {
          success = false;
          FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          return true;
        },
      );

  /// 运行参数为空处理函数
  void handlerEmpty(data) {
    isHidden = true;

    update();
  }

  /// 下发参数后处理
  void afterConfirmSet(bool success, {Map<String, dynamic>? data}) {
    if (success && data != null) {
      model.deviceData.addEntries(data.entries);
    }

    editType = -1;
    update();
  }

  @override
  void onClose() async {
    await onlineStatusSubscription?.cancel();
    await onlineStatusSubsribe.closeListen();
    await subscription?.cancel();
    await subsribe.closeListen();
    super.onClose();
  }
}
